//
//  LYTextView.swift
//  EmoticonKeyboard
//
//  Created by liuerying on 16/6/1.
//  Copyright © 2016年 liuerying. All rights reserved.
//

import UIKit

class LYTextView: UITextView {


    func insertEmoticon(em:LYEmoticon){
    
        //如果点击的空白的模型
        if em.isEmpty{
        
            return
        }
        
        if em.isDelete{
        
            deleteBackward()
            return
            
        }
        
        if em.emoji != nil {
        
            replaceRange(selectedTextRange!, withText: em.emoji ?? "")
            return
        }
        
        let imageText = LYTextAttachment.emoticonImageToImageText(em, font: font!)
        
   
        let strM = NSMutableAttributedString(attributedString: attributedText)
    
        //在替换之前 记录光标所在的位置
        let range = selectedRange
        
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        
        attributedText = strM
        
        selectedRange = NSMakeRange(range.location + 1, 0)
        //主动调用协议方法
        self.delegate?.textViewDidChange?(self)
    }
    
    func fullText() ->String{
    
        let attr = attributedText
        var strM  = String()
        
        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) in
            
            if let attachment = dict["NSAttachment"]as? LYTextAttachment{
            
                strM += (attachment.chs ?? "")
            }else{
            
                let subStr = (self.text as NSString).substringWithRange(range)
                
                strM += subStr
                
            }
        }
        
        return strM
    }

}
